using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using SheLife.Domain.Entities;
using SheLife.Domain.Interfaces;
using SheLife.Domain.Interfaces.Repositories;
using SheLife.Infrastructure.Data;

namespace SheLife.Infrastructure
{
    /// <summary>
    /// 工作单元实现类
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private readonly SheLifeDbContext _context;
        private readonly ILogger<UnitOfWork> _logger;
        private IDbContextTransaction? _transaction;

        // 用户管理相关仓储
        private IUserRepository? _userRepository;
        private IMenstrualCycleRepository? _menstrualCycleRepository;
        private IMenstrualSymptomRepository? _menstrualSymptomRepository;
        private IMenstrualNoteRepository? _menstrualNoteRepository;
        private IBasalBodyTemperatureRepository? _basalBodyTemperatureRepository;

        // 膳食管理相关仓储
        private IDietRecordRepository? _dietRecordRepository;
        private IDietNutrientRepository? _dietNutrientRepository;
        private IRecipeRepository? _recipeRepository;
        private IRecipeIngredientRepository? _recipeIngredientRepository;
        private IRecipeStepRepository? _recipeStepRepository;
        private IRecipeNutrientRepository? _recipeNutrientRepository;
        private IUserRecipeRepository? _userRecipeRepository;

        // 护肤管理相关仓储
        private ISkincareRecordRepository? _skincareRecordRepository;
        private ISkincareProductRepository? _skincareProductRepository;
        private ISkincareRecordProductRepository? _skincareRecordProductRepository;
        private ISkincareProductIngredientRepository? _skincareProductIngredientRepository;
        private ISkincareProductReviewRepository? _skincareProductReviewRepository;
        private ISkincareProductReminderRepository? _skincareProductReminderRepository;
        private ISkincareSkinAnalysisRepository? _skincareSkinAnalysisRepository;

        // 穿搭管理相关仓储
        private IClothingRepository? _clothingRepository;
        private IOutfitRepository? _outfitRepository;
        private IOutfitClothingRepository? _outfitClothingRepository;
        private IOutfitRecordRepository? _outfitRecordRepository;
        private IOutfitTemplateRepository? _outfitTemplateRepository;
        private IOutfitTemplateItemRepository? _outfitTemplateItemRepository;
        private IUserOutfitTemplateRepository? _userOutfitTemplateRepository;
        private IOutfitSuggestionRepository? _outfitSuggestionRepository;

        // 成长管理相关仓储
        private IGrowthGoalRepository? _growthGoalRepository;
        private IGrowthGoalTaskRepository? _growthGoalTaskRepository;
        private IGrowthGoalRecordRepository? _growthGoalRecordRepository;
        private IGrowthHabitRepository? _growthHabitRepository;
        private IGrowthHabitRecordRepository? _growthHabitRecordRepository;
        private IGrowthHabitReminderRepository? _growthHabitReminderRepository;
        private IGrowthHabitPartnerRepository? _growthHabitPartnerRepository;
        private IGrowthHabitChallengeRepository? _growthHabitChallengeRepository;
        private IGrowthHabitChallengeRecordRepository? _growthHabitChallengeRecordRepository;
        private IGrowthHabitRewardRepository? _growthHabitRewardRepository;
        private IGrowthHabitStatisticsRepository? _growthHabitStatisticsRepository;
        private IGrowthGoalTemplateRepository? _growthGoalTemplateRepository;
        private IGrowthHabitTemplateRepository? _growthHabitTemplateRepository;

        // 社区社交相关仓储
        private ICommunityPostRepository? _communityPostRepository;
        private ICommunityPostCommentRepository? _communityPostCommentRepository;
        private ICommunityPostLikeRepository? _communityPostLikeRepository;
        private ICommunityPostFavoriteRepository? _communityPostFavoriteRepository;
        private ICommunityPostReportRepository? _communityPostReportRepository;
        private ICommunityCategoryRepository? _communityCategoryRepository;
        private ICommunityTagRepository? _communityTagRepository;
        private ICommunityPostTagRepository? _communityPostTagRepository;
        private ICommunityUserFollowRepository? _communityUserFollowRepository;
        private ICommunityUserBlockRepository? _communityUserBlockRepository;
        private ICommunityPostStatisticsRepository? _communityPostStatisticsRepository;

        // 通知提醒相关仓储
        private INotificationRepository? _notificationRepository;

        // 系统设置相关仓储
        private ISystemConfigRepository? _systemConfigRepository;
        private ISystemLogRepository? _systemLogRepository;
        private ISystemTaskRepository? _systemTaskRepository;
        private ISystemVersionRepository? _systemVersionRepository;
        private ISystemBackupRepository? _systemBackupRepository;
        private ISystemCacheRepository? _systemCacheRepository;
        private ISystemPermissionRepository? _systemPermissionRepository;
        private IUserPermissionRepository? _userPermissionRepository;
        private ISystemRoleRepository? _systemRoleRepository;
        private IUserRoleRepository? _userRoleRepository;
        private IRolePermissionRepository? _rolePermissionRepository;
        private ISystemUserRepository? _systemUserRepository;
        private ISystemMenuRepository? _systemMenuRepository;
        private IRoleMenuRepository? _roleMenuRepository;
        private ISystemDictionaryRepository? _systemDictionaryRepository;
        private ISystemRegionRepository? _systemRegionRepository;
        private ISystemMessageTemplateRepository? _systemMessageTemplateRepository;

        public UnitOfWork(SheLifeDbContext context, ILogger<UnitOfWork> logger)
        {
            _context = context;
            _logger = logger;
        }

        // 用户管理相关仓储
        public IUserRepository UserRepository => _userRepository ??= new Repository<User>(_context);
        public IMenstrualCycleRepository MenstrualCycleRepository => _menstrualCycleRepository ??= new Repository<MenstrualCycle>(_context);
        public IMenstrualSymptomRepository MenstrualSymptomRepository => _menstrualSymptomRepository ??= new Repository<MenstrualSymptom>(_context);
        public IMenstrualNoteRepository MenstrualNoteRepository => _menstrualNoteRepository ??= new Repository<MenstrualNote>(_context);
        public IBasalBodyTemperatureRepository BasalBodyTemperatureRepository => _basalBodyTemperatureRepository ??= new Repository<BasalBodyTemperature>(_context);

        // 膳食管理相关仓储
        public IDietRecordRepository DietRecordRepository => _dietRecordRepository ??= new Repository<DietRecord>(_context);
        public IDietNutrientRepository DietNutrientRepository => _dietNutrientRepository ??= new Repository<DietNutrient>(_context);
        public IRecipeRepository RecipeRepository => _recipeRepository ??= new Repository<Recipe>(_context);
        public IRecipeIngredientRepository RecipeIngredientRepository => _recipeIngredientRepository ??= new Repository<RecipeIngredient>(_context);
        public IRecipeStepRepository RecipeStepRepository => _recipeStepRepository ??= new Repository<RecipeStep>(_context);
        public IRecipeNutrientRepository RecipeNutrientRepository => _recipeNutrientRepository ??= new Repository<RecipeNutrient>(_context);
        public IUserRecipeRepository UserRecipeRepository => _userRecipeRepository ??= new Repository<UserRecipe>(_context);

        // 护肤管理相关仓储
        public ISkincareRecordRepository SkincareRecordRepository => _skincareRecordRepository ??= new Repository<SkincareRecord>(_context);
        public ISkincareProductRepository SkincareProductRepository => _skincareProductRepository ??= new Repository<SkincareProduct>(_context);
        public ISkincareRecordProductRepository SkincareRecordProductRepository => _skincareRecordProductRepository ??= new Repository<SkincareRecordProduct>(_context);
        public ISkincareProductIngredientRepository SkincareProductIngredientRepository => _skincareProductIngredientRepository ??= new Repository<SkincareProductIngredient>(_context);
        public ISkincareProductReviewRepository SkincareProductReviewRepository => _skincareProductReviewRepository ??= new Repository<SkincareProductReview>(_context);
        public ISkincareProductReminderRepository SkincareProductReminderRepository => _skincareProductReminderRepository ??= new Repository<SkincareProductReminder>(_context);
        public ISkincareSkinAnalysisRepository SkincareSkinAnalysisRepository => _skincareSkinAnalysisRepository ??= new Repository<SkincareSkinAnalysis>(_context);

        // 穿搭管理相关仓储
        public IClothingRepository ClothingRepository => _clothingRepository ??= new Repository<Clothing>(_context);
        public IOutfitRepository OutfitRepository => _outfitRepository ??= new Repository<Outfit>(_context);
        public IOutfitClothingRepository OutfitClothingRepository => _outfitClothingRepository ??= new Repository<OutfitClothing>(_context);
        public IOutfitRecordRepository OutfitRecordRepository => _outfitRecordRepository ??= new Repository<OutfitRecord>(_context);
        public IOutfitTemplateRepository OutfitTemplateRepository => _outfitTemplateRepository ??= new Repository<OutfitTemplate>(_context);
        public IOutfitTemplateItemRepository OutfitTemplateItemRepository => _outfitTemplateItemRepository ??= new Repository<OutfitTemplateItem>(_context);
        public IUserOutfitTemplateRepository UserOutfitTemplateRepository => _userOutfitTemplateRepository ??= new Repository<UserOutfitTemplate>(_context);
        public IOutfitSuggestionRepository OutfitSuggestionRepository => _outfitSuggestionRepository ??= new Repository<OutfitSuggestion>(_context);

        // 成长管理相关仓储
        public IGrowthGoalRepository GrowthGoalRepository => _growthGoalRepository ??= new Repository<GrowthGoal>(_context);
        public IGrowthGoalTaskRepository GrowthGoalTaskRepository => _growthGoalTaskRepository ??= new Repository<GrowthGoalTask>(_context);
        public IGrowthGoalRecordRepository GrowthGoalRecordRepository => _growthGoalRecordRepository ??= new Repository<GrowthGoalRecord>(_context);
        public IGrowthHabitRepository GrowthHabitRepository => _growthHabitRepository ??= new Repository<GrowthHabit>(_context);
        public IGrowthHabitRecordRepository GrowthHabitRecordRepository => _growthHabitRecordRepository ??= new Repository<GrowthHabitRecord>(_context);
        public IGrowthHabitReminderRepository GrowthHabitReminderRepository => _growthHabitReminderRepository ??= new Repository<GrowthHabitReminder>(_context);
        public IGrowthHabitPartnerRepository GrowthHabitPartnerRepository => _growthHabitPartnerRepository ??= new Repository<GrowthHabitPartner>(_context);
        public IGrowthHabitChallengeRepository GrowthHabitChallengeRepository => _growthHabitChallengeRepository ??= new Repository<GrowthHabitChallenge>(_context);
        public IGrowthHabitChallengeRecordRepository GrowthHabitChallengeRecordRepository => _growthHabitChallengeRecordRepository ??= new Repository<GrowthHabitChallengeRecord>(_context);
        public IGrowthHabitRewardRepository GrowthHabitRewardRepository => _growthHabitRewardRepository ??= new Repository<GrowthHabitReward>(_context);
        public IGrowthHabitStatisticsRepository GrowthHabitStatisticsRepository => _growthHabitStatisticsRepository ??= new Repository<GrowthHabitStatistics>(_context);
        public IGrowthGoalTemplateRepository GrowthGoalTemplateRepository => _growthGoalTemplateRepository ??= new Repository<GrowthGoalTemplate>(_context);
        public IGrowthHabitTemplateRepository GrowthHabitTemplateRepository => _growthHabitTemplateRepository ??= new Repository<GrowthHabitTemplate>(_context);

        // 社区社交相关仓储
        public ICommunityPostRepository CommunityPostRepository => _communityPostRepository ??= new Repository<CommunityPost>(_context);
        public ICommunityPostCommentRepository CommunityPostCommentRepository => _communityPostCommentRepository ??= new Repository<CommunityPostComment>(_context);
        public ICommunityPostLikeRepository CommunityPostLikeRepository => _communityPostLikeRepository ??= new Repository<CommunityPostLike>(_context);
        public ICommunityPostFavoriteRepository CommunityPostFavoriteRepository => _communityPostFavoriteRepository ??= new Repository<CommunityPostFavorite>(_context);
        public ICommunityPostReportRepository CommunityPostReportRepository => _communityPostReportRepository ??= new Repository<CommunityPostReport>(_context);
        public ICommunityCategoryRepository CommunityCategoryRepository => _communityCategoryRepository ??= new Repository<CommunityCategory>(_context);
        public ICommunityTagRepository CommunityTagRepository => _communityTagRepository ??= new Repository<CommunityTag>(_context);
        public ICommunityPostTagRepository CommunityPostTagRepository => _communityPostTagRepository ??= new Repository<CommunityPostTag>(_context);
        public ICommunityUserFollowRepository CommunityUserFollowRepository => _communityUserFollowRepository ??= new Repository<CommunityUserFollow>(_context);
        public ICommunityUserBlockRepository CommunityUserBlockRepository => _communityUserBlockRepository ??= new Repository<CommunityUserBlock>(_context);
        public ICommunityPostStatisticsRepository CommunityPostStatisticsRepository => _communityPostStatisticsRepository ??= new Repository<CommunityPostStatistics>(_context);

        // 通知提醒相关仓储
        public INotificationRepository NotificationRepository => _notificationRepository ??= new Repository<Notification>(_context);

        // 系统设置相关仓储
        public ISystemConfigRepository SystemConfigRepository => _systemConfigRepository ??= new Repository<SystemConfig>(_context);
        public ISystemLogRepository SystemLogRepository => _systemLogRepository ??= new Repository<SystemLog>(_context);
        public ISystemTaskRepository SystemTaskRepository => _systemTaskRepository ??= new Repository<SystemTask>(_context);
        public ISystemVersionRepository SystemVersionRepository => _systemVersionRepository ??= new Repository<SystemVersion>(_context);
        public ISystemBackupRepository SystemBackupRepository => _systemBackupRepository ??= new Repository<SystemBackup>(_context);
        public ISystemCacheRepository SystemCacheRepository => _systemCacheRepository ??= new Repository<SystemCache>(_context);
        public ISystemPermissionRepository SystemPermissionRepository => _systemPermissionRepository ??= new Repository<SystemPermission>(_context);
        public IUserPermissionRepository UserPermissionRepository => _userPermissionRepository ??= new Repository<UserPermission>(_context);
        public ISystemRoleRepository SystemRoleRepository => _systemRoleRepository ??= new Repository<SystemRole>(_context);
        public IUserRoleRepository UserRoleRepository => _userRoleRepository ??= new Repository<UserRole>(_context);
        public IRolePermissionRepository RolePermissionRepository => _rolePermissionRepository ??= new Repository<RolePermission>(_context);
        public ISystemUserRepository SystemUserRepository => _systemUserRepository ??= new Repository<SystemUser>(_context);
        public ISystemMenuRepository SystemMenuRepository => _systemMenuRepository ??= new Repository<SystemMenu>(_context);
        public IRoleMenuRepository RoleMenuRepository => _roleMenuRepository ??= new Repository<RoleMenu>(_context);
        public ISystemDictionaryRepository SystemDictionaryRepository => _systemDictionaryRepository ??= new Repository<SystemDictionary>(_context);
        public ISystemRegionRepository SystemRegionRepository => _systemRegionRepository ??= new Repository<SystemRegion>(_context);
        public ISystemMessageTemplateRepository SystemMessageTemplateRepository => _systemMessageTemplateRepository ??= new Repository<SystemMessageTemplate>(_context);

        public async Task<int> SaveChangesAsync()
        {
            try
            {
                return await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存更改时发生错误");
                throw;
            }
        }

        public async Task BeginTransactionAsync()
        {
            if (_transaction != null)
            {
                throw new InvalidOperationException("事务已开始");
            }

            _transaction = await _context.Database.BeginTransactionAsync();
        }

        public async Task CommitTransactionAsync()
        {
            try
            {
                if (_transaction == null)
                {
                    throw new InvalidOperationException("未开始事务");
                }

                await _context.SaveChangesAsync();
                await _transaction.CommitAsync();
            }
            catch (Exception ex)
            {
                await RollbackTransactionAsync();
                _logger.LogError(ex, "提交事务时发生错误");
                throw;
            }
            finally
            {
                if (_transaction != null)
                {
                    await _transaction.DisposeAsync();
                    _transaction = null;
                }
            }
        }

        public async Task RollbackTransactionAsync()
        {
            try
            {
                if (_transaction != null)
                {
                    await _transaction.RollbackAsync();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "回滚事务时发生错误");
                throw;
            }
            finally
            {
                if (_transaction != null)
                {
                    await _transaction.DisposeAsync();
                    _transaction = null;
                }
            }
        }

        public void Dispose()
        {
            _transaction?.Dispose();
            _context.Dispose();
        }
    }
}